package com.iweb.dao;

import com.iweb.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/*
 *作者：lth
 *时间：2020/8/11 17:59
 *描述：
 */
public class UserDaoImpl implements UserDao {
    private PreparedStatement pst;
    private Connection conn;
    private ResultSet rs;

    public UserDaoImpl(Connection connection) {
        this.conn = connection;
    }

    @Override
    public void save(User user) throws Exception {
        String sql = "insert into tb_user (userid,username,password) values (?,?,?)";

        pst = conn.prepareStatement(sql);
        pst.setString(1, user.getUserid());
        pst.setString(2, user.getUsername());
        pst.setString(3, user.getPassword());
        pst.executeUpdate();
    }

    @Override
    public User findByUserId(String userid) throws Exception {
        User user = null;
        String sql = "select * from tb_user where userid = ?";
        pst = conn.prepareStatement(sql);
        pst.setObject(1, userid);
        rs = pst.executeQuery();

        while (rs.next()) {
            user = createInstance(rs);
        }
        return user;
    }

    //返回用户总数
    @Override
    public long selectCount() throws Exception {
        String sql = "select count(1) from tb_user";
        pst = conn.prepareStatement(sql);
        rs = pst.executeQuery();
        rs.next();
        return rs.getLong(1);
    }

    private User createInstance(ResultSet rs) throws Exception {
        User user = new User();
        user.setUserid(rs.getString("userid"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setPhone(rs.getString("phone"));
        return user;
    }
}
